<script>
import fieldConfig from '../fieldConfig.vue'
import WrapTable from '@/components/WrapTable'
import SearchForm from '@/components/SearchForm'
import TableButtonList from '@/components/TableButtonList'
import ButtonList from '@/components/ButtonList'
import DialogForm from '@/components/DialogForm'
import addtable from '@/mixins/addtable'
import AjaxStore from '@/utils/store/proxyAjax'
import request from '@/utils/request'
import store from './store.js'

export default {
  name: 'addtableright',
  mixins: [addtable, store],
  inject: ['Dialog'],
  components: {
    ButtonList,
    DialogForm,
    WrapTable,
    SearchForm,
    TableButtonList,
    fieldConfig
  },
  provide() {
    return {
      addtableright: this
    }
  },
  props: {
    datagroupId: {
      type: String,
      default: ''
    },
    datagroupName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      rowIndex: 0,
      currentRow: {},
      selectList: [],
      copyChooseTchIds: [],
      dbArr: [],
      selectedList: [],
      tableOptWidth: '120',
      dialogType: '',
      idKey: 'applyIds',
      allFields: [],
      getFiedlistUrl: '/v1/yq/datagroup/getFieldByTableId',
      getDbUrl: '/v1/yq/datagroup/getDbList',
      getCateUrl: '/v1/yq/datagroup/getCateList',
      getAllFieldUrl: '/v1/yq/datagroup/getFieldByTableId',
      store: new AjaxStore({
        url: '/v1/yq/datagroup/queryTableList'
      }),
      model: {
        dbname: '',
        firstname: '',
        secondname: '',
        tablename: '',
        fields: ''
      },
      columns: [
        {
          prop: 'dbName',
          label: '数据源',
          sortable: true,
          'min-width': '120',
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'firstName',
          label: '一级分类',
          sortable: true,
          'min-width': '120',
          'header-align': 'center',
          'show-overflow-tooltip': true
        },
        {
          prop: 'secondName',
          label: '二级分类',
          sortable: true,
          'min-width': '120',
          'header-align': 'center',
          'show-overflow-tooltip': true
        },
        {
          prop: 'tableName',
          label: '表',
          sortable: true,
          'min-width': '120',
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'fields',
          label: '授予字段',
          sortable: true,
          'show-overflow-tooltip': true,
          'min-width': '240',
          'header-align': 'center',
          scopedSlots: {
            default: scope => {
              return <div class='table-config-field'></div>
            }
          }
        }
      ],
      searchModel: {
        dbId: '',
        firstCateId: '',
        secondCateId: '',
        tableName: ''
      },
      searchFields: [
        {
          label: '数据源',
          prop: 'dbId',
          placeholder: '请选择数据源',
          anchor: 8,
          xType: 'SelectConfig',
          isLocal: false,
          relatedFields: ['firstCateId', 'secondCateId'],
          ref: 'dbId',
          getData: params => {
            return request({
              url: this.getDbUrl,
              method: 'post',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              data: params
            }).then(({ data }) => {
              return data.map(item => {
                return {
                  value: item.objId,
                  label: item.dbName
                }
              })
            })
          }
        },
        {
          label: '一级分类',
          prop: 'firstCateId',
          placeholder: '请选择一级分类',
          anchor: 8,
          xType: 'SelectConfig',
          autoLoad: false,
          isLocal: false,
          relatedFields: ['secondCateId'],
          ref: 'firstCateId',
          on: {
            'el.form.update': (val, ctx, origin, form) => {
              form.model.firstCateId = ''
              ctx.load({ dbId: this.searchModel.dbId })
            },
            'visible-change': val => {
              const params = {
                dbId: this.searchModel.dbId
              }
              val && this.$refs.searchForm.$refs.firstCateId.load(params)
            }
          },
          getData: params => {
            if (params && params.dbId) {
              return request({
                url: this.getCateUrl,
                method: 'post',
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: params
              }).then(({ data }) => {
                return data.map(item => {
                  return {
                    value: item.objId,
                    label: item.cateName
                  }
                })
              })
            } else {
              return Promise.resolve([])
            }
          }
        },
        {
          label: '二级分类',
          prop: 'secondCateId',
          placeholder: '请选择二级分类',
          anchor: 8,
          xType: 'SelectConfig',
          autoLoad: false,
          isLocal: false,
          ref: 'secondCateId',
          on: {
            'el.form.update': (val, ctx, origin, form) => {
              form.model.secondCateId = ''
              ctx.load({ dbId: form.model.dbId, pid: form.model.firstCateId })
            }
          },
          getData: params => {
            if (params && params.dbId && params.pid) {
              return request({
                url: this.getCateUrl,
                method: 'post',
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: params
              }).then(({ data }) => {
                return data.map(item => {
                  return {
                    value: item.objId,
                    label: item.cateName
                  }
                })
              })
            } else {
              return Promise.resolve([])
            }
          }
        },
        {
          label: '表名称',
          prop: 'tableName',
          placeholder: '请输入表名称',
          anchor: 8
        }
      ],
      searchBtnList: this.searchBtns,
      toolPanelBtnList: []
      // tableRowBtnList: []
    }
  },
  watch: {
    'Dialog.visible': {
      immediate: true,
      handler(val) {
        val &&
          this.$nextTick(() => {
            val && this.setDefaultDb()
          })
      }
    }
  },
  methods: {
    setDefaultDb() {
      return request({
        url: this.getDbUrl,
        method: 'post'
      }).then(({ success, data }) => {
        if (success && data.length > 0) {
          // 设置默认数据源
          this.searchModel.dbId = data[0].objId
          this.handleSearch()
        }
      })
    },
    getSearchModelData() {
      const { dbId, firstCateId, secondCateId, tableName } = this.searchModel
      return {
        dbId,
        firstCateId,
        secondCateId,
        tableName,
        datagroupId: this.datagroupId
      }
    },
    getData({ page, limit }) {
      this.store && (this.store._searchParams.datagroupId = this.datagroupId)
      this.store.read({ start: page, limit: limit })
      this.clearColumn()
    },
    clearColumn() {
      this.data.map(item => {
        if (item.fields) {
          item.fields = ''
          item.fieldsAll = []
        }
      })
      const domList = document.getElementsByClassName('table-config-field')
      const domListLength = domList.length
      for (let i = 0; i < domListLength; i++) {
        domList[i].innerText = ''
      }
      this.selectedList = []
    },
    handleSearch() {
      const model = this.searchModel
      for (const k in model) {
        this.store._searchParams[k] = model[k]
      }
      if (!model.dbId) {
        this.$message({
          customClass: 'datagroup-message',
          type: 'info',
          message: '数据源必选！'
        })
        return
      }
      this.store._searchParams['datagroupId'] = this.datagroupId
      this.clearColumn()
      this.$refs.table.load(1, this.store.limit)
    },
    handleWordConfig(row) {
      this.rowIndex = this.data.findIndex(item => item.tableId === row.tableId)
      this.currentRow = row
      this.getAllField({ q_tableId: row.tableId, start: 1, limit: 99999 })
        .then(({ success, data }) => {
          if (success) {
            this.allFields = data
            this.userIds = row.fieldsAll
            this.tableId = row.tableId
            this.tableConfigId = row.tableConfigId
            this.tableName = row.tablename
            this.dialogType = 'fieldConfig'
          } else {
            this.$message({
              customClass: 'datagroup-message',
              type: 'error',
              message: '获取表内所有字段失败！'
            })
          }
        })
        .catch(err => console.log(err))
    },
    handleSelectionChange(selection) {
      // console.log('selection', selection)
    },
    handleReset() {
      this.searchModel.dbId = ''
      this.searchModel.firstCateId = ''
      this.searchModel.secondCateId = ''
      this.handleSearch()
    },
    handleSelect(selection, row) {
      this.rowIndex = this.data.findIndex(item => item.tableId === row.tableId)
      this.currentRow = row
      const data = this.data
      this.selectedList = JSON.parse(JSON.stringify(selection))
      const selectedIndex = this.selectedList.findIndex(
        item => item.tableId === row.tableId
      )
      // 判断是勾选还是取消勾选
      const isSelected = selection.length && selection.indexOf(row) !== -1
      if (isSelected) {
        this.getFiedlist({ q_tableId: row.tableId, start: 1, limit: 99999 })
          .then(({ data }) => {
            const fields = data
              .map(item => {
                return item.ename
              })
              .join(',')

            const fieldsText = data
              .map(item => {
                return item.cname
              })
              .join(',')

            if (data.length) {
              row.fields = fields
              row.fieldsAll = data
              this.selectedList[selectedIndex].fields = fields
              this.selectedList[selectedIndex].fieldsAll = data
              document.getElementsByClassName('table-config-field')[
                this.rowIndex
              ].innerText = fieldsText
            }
          })
          .catch(err => {
            console.log('err', err)
          })
      } else {
        row.fields = ''
        row.fieldsAll = []
        document.getElementsByClassName('table-config-field')[
          this.rowIndex
        ].innerText = ''
      }
    },
    handleAddRightSave() {
      const selectField = this.$refs.fieldConfig.handleReturnSelectedList()
      const selectedIndex = this.selectedList.findIndex(
        item => item.tableId === this.currentRow.tableId
      )
      const fields = selectField
        .map(item => {
          return item.ename
        })
        .join(',')
      const fieldsText = selectField.map(item => {
        return item.cname
      })
      this.currentRow.fields = fields
      this.currentRow.fieldsAll = selectField
      document.getElementsByClassName('table-config-field')[
        this.rowIndex
      ].innerText = fieldsText
      this.dialogType = ''
      if (selectField.length) {
        this.selectedList.splice(selectedIndex, 1)
        this.selectedList.push(this.currentRow)
        this.$refs.table.toggleRowSelection(this.currentRow, true)
      } else {
        this.selectedList.splice(selectedIndex, 1)
        this.$refs.table.toggleRowSelection(this.currentRow, false)
      }
    },
    handleCancel() {
      this.$refs.fieldConfig.handleEmptySelectedList()
      this.userIds = []
      this.tableId = ''
      this.tableConfigId = ''
      this.tableName = ''
      this.dialogType = ''
    },
    handleSelectAll(selection) {
      const dom = document.getElementsByClassName('table-config-field')
      const length = selection.length
      if (length) {
        this.selectedList = selection
        for (let i = 0; i < length; i++) {
          this.getAllField({
            q_tableId: selection[i].tableId,
            start: 1,
            limit: 99999
          })
            .then(({ success, data }) => {
              if (success) {
                dom[i].innerText = data
                  .map(item => {
                    return item.cname
                  })
                  .join(',')
                this.selectedList[i].fields = data
                  .map(item => {
                    return item.ename
                  })
                  .join(',')
                this.selectedList[i].fieldsAll = data
              } else {
                this.$message({
                  customClass: 'datagroup-message',
                  type: 'error',
                  message: '获取表内所有字段失败！'
                })
              }
            })
            .catch(err => {
              console.log('err', err)
            })
        }
      } else {
        for (let j = 0, len = this.data.length; j < len; j++) {
          dom[j].innerText = ''
          this.data[j].fields = ''
          this.data[j].fieldsAll = []
          this.selectedList = []
        }
      }
    },
    renderWrapTable(h) {
      return (
        <WrapTable
          ref='table'
          selectionCol={this.tableSelectionCol}
          getData={this.getData}
          total={this.total}
          data={this.data}
          fields={this.columns}
          tooltip-effect='dark'
          autoLoad={false}
          pagination={true}
          border
          stripe
          default-sort={{ prop: 'maintainFlag', order: 'descending' }}
          on-selection-change={this.handleSelectionChange}
          on-select={this.handleSelect}
          on-select-all={this.handleSelectAll}>
          <SearchForm
            defaultItemsLength={4}
            items={this.searchFields}
            props-model={this.searchModel}
            slot='searchPanel'
            ref='searchForm'>
            <ButtonList
              operateBtnList={this.searchBtnList}
              props-model={this.searchModel}></ButtonList>
          </SearchForm>

          <c-table-column
            label='操作'
            align='center'
            slot='toolbar'
            fixed='right'
            width={this.tableOptWidth}
            {...{
              scopedSlots: {
                default: scope => {
                  return (
                    <TableButtonList
                      operateBtnList={this.tableConfigBtns}
                      props-model={scope.row}></TableButtonList>
                  )
                }
              }
            }}></c-table-column>
        </WrapTable>
      )
    },
    renderCustom(h) {
      return (
        <DialogForm
          closeOnClickModal={false}
          width='720px'
          class='fieldConfig-dialog'
          visible={this.dialogType === 'fieldConfig'}
          title={`数据组${this.datagroupName}的${this.tableName}表字段权限配置`}
          appendToBody={true}
          on-close={this.handleCancel}>
          <fieldConfig
            ref='fieldConfig'
            allFields={this.allFields}
            tableId={this.tableId}
            userIds={this.userIds}
          />
          <c-form ref='form' slot='footer'>
            <c-form-item class='submit-btn'>
              <ButtonList operateBtnList={this.submitBtns}></ButtonList>
            </c-form-item>
          </c-form>
        </DialogForm>
      )
    }
  },
  render(h) {
    return (
      <div class='addtableright addtable-right'>
        {this.renderWrapTable(h)}
        {this.renderCustom(h)}
      </div>
    )
  },
  beforeCreate() {
    // 根据页面路由找出有权限访问的 url 数组
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    )

    this.searchBtns = [
      {
        label: '查询',
        methods: 'handleSearch',
        url: '',
        icon: 'el-icon-search',
        type: 'primary',
        disabled: false
      }
      // { label: '重置', methods: 'handleSearchReset', url: '', icon: 'iconxianxing_zhongzhi', type: 'warning', disabled: false }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.tableConfigBtns = [
      {
        label: '字段配置',
        methods: 'handleWordConfig',
        url: '/v1/yq/datagroup/addTableConfig',
        svgIcon: 'mdtjconfig',
        type: 'primary',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.submitBtns = [
      {
        label: '保存',
        methods: 'handleAddRightSave',
        url: '/v1/yq/datagroup/addTableConfig',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleCancel',
        url: '/v1/yq/datagroup/addTableConfig',
        icon: 'el-icon-circle-close-outline',
        type: 'primary',
        disabled: false
      }
    ].filter(item => item.url && urlArr.includes(item.url))
  }
}
</script>

<style lang="scss">
.addtableright {
  .wrap-table {
    .searchPanel,
    .cp-search-form {
      padding-bottom: 0;
      .el-form {
        .fields-box {
          width: 94% !important;
        }
      }
      .see-more {
        display: none;
      }
      .search-btn-box {
        bottom: 0;
      }
    }
    .el-pagination__sizes {
      // display: none;
      .el-select {
        width: 80px;
      }
    }
  }
}
.el-tooltip__popper {
  max-width: 500px;
  word-wrap: break-word;
}
</style>
